import ResizeObserver from 'resize-observer-polyfill'

let robserver = null

export default {
  bind: function (el, binding) {},
  inserted: function (el, binding) {
    robserver = new ResizeObserver(entries => {
      const { value } = binding
      const bottomOffset = (value && value.bottomOffset) || 0
      const callback = value.callback
      const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
      callback && callback(height)
    })
    robserver.observe(window.document.body)
  },
  update: function (el, binding) {
    robserver = new ResizeObserver(entries => {
      const { value } = binding
      const bottomOffset = (value && value.bottomOffset) || 0
      const callback = value.callback
      const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
      callback && callback(height)
    })
    robserver.observe(window.document.body)
  },
  unbind: function (el, binding) {
    robserver && robserver.disconnect()
    robserver = null
  }
}
